package com.pzr.soccer.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author pzr
 * @date:2022-01-02-8:40
 * @Description:
 **/
@Slf4j
public class UserUtil {

    public static Map<String,Object> parserUserFromSecurityContext(){
        try{
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            JSONObject jsonObject= JSON.parseObject(JSON.toJSONString(authentication.getPrincipal()));
            Map<String,Object> map=new HashMap<>();
            map.put("id",jsonObject.getString("id"));
            map.put("username", jsonObject.getString("username"));
            map.put("email", jsonObject.getString("email"));
            map.put("mobile",jsonObject.getString("mobile"));
            map.put("qq", jsonObject.getString("qq"));
            map.put("aliPay", jsonObject.getString("aliPay"));
            map.put("weChat", jsonObject.getString("weChat"));
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            map.put("authorities",authorities);
            return  map;
        }catch (Exception e){
            log.error("pare soccer from security context failed!");
            return null;
        }
    }
}
